package com.homegoods.home.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bigkoo.convenientbanner.Banner;
import com.bigkoo.convenientbanner.PageIndicatorAlign;
import com.bigkoo.convenientbanner.holder.CBViewHolderCreator;
import com.bigkoo.convenientbanner.holder.Holder;
import com.bigkoo.convenientbanner.listener.OnItemClickListener;
import com.homegoods.home.R;
import com.homegoods.home.model.HomeClassModel;
import com.homegoods.home.model.HomeGroupsModel;
import com.homegoods.home.model.SubHomeClassModel;
import com.homegoods.resource.Constant;
import com.homegoods.resource.ILifecycle;
import com.kedll.library.util.BindingUtil;
import com.kedll.library.util.MyUtils;

import java.util.List;


/**
 * TODO: document your custom view class.
 *
 * @author QiQi
 */
public class HomeHeadView extends FrameLayout implements ILifecycle {
    private static final String TAG = "HomeHeadViewTag";

    Banner<String> convenientBanner;
    GridView expandedMenu;

    MenuAdapter adapter;

    AdapterView.OnItemClickListener onItemClickListener;
    OnItemClickListener onBannerClickListener;
    Context mContext;
    int adWidth;
    int adHeight;

    public HomeHeadView(Context context) {
        this(context, null);
    }

    public HomeHeadView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }


    public HomeHeadView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        LayoutInflater.from(context).inflate(R.layout.home_head_layout, this, true);
        mContext = context;
        adWidth = MyUtils.getDisplayWidth(context);
        adHeight = MyUtils.dp2px(100);
        convenientBanner = findViewById(R.id.convenientBanner);
        expandedMenu = findViewById(R.id.expandedMenu);
        initEvent(context, attrs);
        initBanner();
    }

    private void initBanner() {
        //初始化轮播图
        convenientBanner.getViewPager().setClipToPadding(false);
        RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) convenientBanner.getViewPager().getLayoutParams();
        params.leftMargin = 0;
        params.rightMargin = 0;
        //modify for shibo.zheng 19/06/25
        params.height = (int) (MyUtils.getDisplayWidth(mContext) / 1.59);   //banner图片的高度 = 屏幕的宽度 * 1.59
        Log.d(TAG, "initBanner: height == " + params.height);
    }

    private void initEvent(Context context, AttributeSet attrs) {
        expandedMenu.setOnItemClickListener((parent, view, position, id) -> {
//            MenuItemVo itemVo = adapter.getItem(position);
            if (onItemClickListener != null) {
                onItemClickListener.onItemClick(parent, view, position, id);
            }
        });

//        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.HomeHeadView);
//        if (typedArray != null) {
//            int drawableRef = typedArray.getResourceId(R.styleable.HomeHeadView_home_menu_icon, -1);
//            int menuNameRef = typedArray.getResourceId(R.styleable.HomeHeadView_home_menu_name, -1);
//
//            if (drawableRef != -1 && menuNameRef != -1) {
//                TypedArray ar = getResources().obtainTypedArray(drawableRef);
//                int[] drawables = new int[ar.length()];
//                for (int i = 0; i < ar.length(); i++) {
//                    drawables[i] = ar.getResourceId(i, 0);
//                }
//                setMenuItems(drawables, menuNameRef);
//            }
//
//            typedArray.recycle();
//        }

    }

    public void setMenuItems(HomeGroupsModel menuItems) {

        int width = getResources().getDisplayMetrics().widthPixels;
        int itemWidth = width / 3;
        int itemHeight = width / 4;


        adapter = new MenuAdapter(getContext(), menuItems, menuItems.getChildren());
        adapter.setWidth(itemWidth);
        adapter.setHeight(itemHeight);
        expandedMenu.setAdapter(adapter);


//        String[] menuNames = getResources().getStringArray(homeMenu);
//        for (int i = 0; i < menuItems.size(); i++) {
//            SubHomeClassModel itemVo = menuItems.get(i);
////            itemVo.name = menuNames[i];
////            itemVo.resId = drawables[i];
//            adapter.add(itemVo);
//        }
    }

    /**
     * TODO 轮播广告点击事件
     *
     * @param l
     */
    public void setOnBannerClickListener(OnItemClickListener l) {
        convenientBanner.setOnItemClickListener(l);
    }

    public void setOnItemClickListener(AdapterView.OnItemClickListener l) {
        this.onItemClickListener = l;
    }

    /**
     * 设置广告
     */
    public void setPage(List<String> images) {
        convenientBanner.setPages(
                (CBViewHolderCreator<NetWorkImageHolderView>) NetWorkImageHolderView::new, images)
                //设置两个点图片作为翻页指示器，不设置则没有指示器，可以根据自己需求自行配合自己的指示器,不需要圆点指示器可用不设
                .setPageIndicator(new int[]{R.mipmap.indicator_normal, R.mipmap.indicator_select})
                //设置指示器的方向
                .setPageIndicatorAlign(PageIndicatorAlign.ALIGN_PARENT_RIGHT)
                /*.setPageTransformer(new ViewPager.PageTransformer() {
                    private static final float min_scale = 0.85f;

                    @Override
                    public void transformPage(View page, float position) {
                        float scaleFactor = Math.max(min_scale, 1 - Math.abs(position));
                        if (position < -1) {
                            page.setScaleX(scaleFactor);
                            page.setScaleY(scaleFactor);
                        } else if (position < 0) {
                            page.setScaleX(scaleFactor);
                            page.setScaleY(scaleFactor);
                        } else if (position >= 0 && position < 1) {
                            page.setScaleX(scaleFactor);
                            page.setScaleY(scaleFactor);
                        } else if (position >= 1) {
                            page.setScaleX(scaleFactor);
                            page.setScaleY(scaleFactor);
                        }
                    }
                })*/;
    }

    @Override
    public void onStart() {
        convenientBanner.startTurning(3000);
    }

    @Override
    public void onStop() {
        convenientBanner.stopTurning();
    }

    @Override
    public void onDestroy() {
        expandedMenu.setOnItemClickListener(null);
    }

    static class ViewHolder {
        TextView text1;
        TextView text2;
        ImageView img;

        ViewHolder(View view) {
            text1 = view.findViewById(android.R.id.text1);
            text2 = view.findViewById(android.R.id.text2);
            img = view.findViewById(R.id.iv_img);
        }
    }

    private class NetWorkImageHolderView implements Holder<String> {
        private ImageView imageView;

        @Override
        public View createView(Context context) {
//            View view = LayoutInflater.from(context).inflate(R.layout.item_ad_layout, null);
//            imageView = view.findViewById(R.id.ad_img);
//            int width = context.getResources().getDisplayMetrics().widthPixels - MyUtils.dp2px(40);
//            int height = (width * 9) / 16;
//            ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(width, height);
//            view.setLayoutParams(params);
            imageView = new ImageView(context);
            return imageView;
        }

        @Override
        public void updateUI(Context context, int position, String data) {
            if (TextUtils.isEmpty(data)) {
                return;
            }
            loadImageByVolley(data);
        }


        /**
         * 利用Volley异步加载图片
         * <p/>
         * 注意方法参数:
         * getImageListener(ImageView view, int defaultImageResId, int errorImageResId)
         * 第一个参数:显示图片的ImageView
         * 第二个参数:默认显示的图片资源
         * 第三个参数:加载错误时显示的图片资源
         */
        private void loadImageByVolley(String imageUrl) {
            BindingUtil.loadImageNoTransform(imageView, imageUrl, null, null);
        }
    }

    private final class MenuAdapter extends BaseAdapter {
        List<HomeGroupsModel.ChildrenBean> menuItems;
        HomeGroupsModel mModel;
        int width;
        int height;

        public MenuAdapter(Context context, HomeGroupsModel model, List<HomeGroupsModel.ChildrenBean> menuItems) {
            this.menuItems = menuItems;
            this.mModel = model;
        }

        public void setWidth(int width) {
            this.width = width;
        }

        public void setHeight(int height) {
            this.height = height;
        }

        @Override
        public int getCount() {
            if (menuItems.size() > 6) {
                return 6;
            } else {
                return menuItems.size();
            }
        }

        @Override
        public Object getItem(int position) {
            return menuItems.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
//            ViewHolder holder = null;
            convertView = null;
//            if (convertView == null) {
            convertView = LayoutInflater.from(getContext()).inflate(R.layout.home_menu_item_layout, null);
            ViewHolder holder = new ViewHolder(convertView);
//                convertView.setTag(111, holder);
            convertView.setLayoutParams(new GridView.LayoutParams(width, GridView.LayoutParams.WRAP_CONTENT));
//            } else {
////                holder = (ViewHolder) convertView.getTag(111);
//            }
            HomeGroupsModel.ChildrenBean itemVo = menuItems.get(position);
            holder.text1.setText(itemVo.getGroupName());
            if (position == 2 || position == 5) {
                holder.img.setVisibility(View.INVISIBLE);
            }
//            holder.img.setImageResource(itemVo.getBgimg());
//            BindingUtil.loadImageNoTransform(holder.img, com.homegoods.classify.model.Constant.SERVER_URL + itemVo.getBgimg(), null, null);
            convertView.setTag(mModel);
            return convertView;
        }
    }

//    private final class MenuItemVo {
//        public int resId;
//        public String name;
//    }
}